#include "modules/drivers/lidar/orin_hesai/common/make_time.h"

#include <cstring>


namespace apollo {
namespace drivers {
namespace lidar_hesai {

int64_t MakeTime::mktime_kernel(tm* tp) const {
  int year = tp->tm_year + 1900;
  int mon = tp->tm_mon + 1;
  int day = tp->tm_mday;
  int hour = tp->tm_hour;
  int min = tp->tm_min;
  int sec = tp->tm_sec;

  // Puts Feb last since it has leap day. 1..12 -> 11,12,1..10
  mon -= 2;
  if (0 >= mon) {
    mon += 12;
    year -= 1;
  }

  int64_t days = static_cast<int64_t>(year / 4 - year / 100 + year / 400 +
                                      kCalcMonthDays * mon / 12 + day) +
                 year * 365 - kEpochOffsetDays;
  int64_t minutes = (days * 24 + hour) * 60 + min;

  return minutes * 60 + sec;
}

MakeTime::MakeTime() {
  struct tm tp;
  tp.tm_year = 100;
  tp.tm_mon = 1;
  tp.tm_mday = 1;
  tp.tm_hour = 1;
  tp.tm_min = 1;
  tp.tm_sec = 1;
  tp.tm_isdst = 0;

  timezone_offset_ = static_cast<int64_t>(::mktime(&tp)) - mktime_kernel(&tp);
  AINFO << "timezone_offset_ is " << timezone_offset_;
}

MakeTime::~MakeTime() {}

time_t MakeTime::mktime(tm* tp) const {
  return static_cast<time_t>(timezone_offset_ + mktime_kernel(tp));
}

}  // namespace lidar_hesai
}  // namespace drivers
}  // namespace apollo